package cn.iocoder.yudao.module.wrzj.service.conversation;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.wrzj.controller.app.conversation.vo.AppConversationPageReqVO;
import cn.iocoder.yudao.module.wrzj.controller.app.conversation.vo.AppConversationSaveReqVO;
import cn.iocoder.yudao.module.wrzj.dal.dataobject.conversation.ConversationDO;
import cn.iocoder.yudao.module.wrzj.dal.mysql.conversation.ConversationMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wrzj.enums.ErrorCodeConstants.CONVERSATION_NOT_EXISTS;

/**
 * chatbase会话记录 Service 实现类
 *
 * @author 运掌科技
 */
@Service
@Validated
public class ConversationServiceImpl implements ConversationService {

    @Resource
    private ConversationMapper conversationMapper;

    @Override
    public Integer createConversation(AppConversationSaveReqVO createReqVO) {
        // 插入
        ConversationDO conversation = BeanUtils.toBean(createReqVO, ConversationDO.class);
        conversationMapper.insert(conversation);
        // 返回
        return conversation.getId();
    }

    @Override
    public void updateConversation(AppConversationSaveReqVO updateReqVO) {
        // 校验存在
        validateConversationExists(updateReqVO.getId());
        // 更新
        ConversationDO updateObj = BeanUtils.toBean(updateReqVO, ConversationDO.class);
        conversationMapper.updateById(updateObj);
    }

    @Override
    public void deleteConversation(Integer id) {
        // 校验存在
        validateConversationExists(id);
        // 删除
        conversationMapper.deleteById(id);
    }

    private void validateConversationExists(Integer id) {
        if (conversationMapper.selectById(id) == null) {
            throw exception(CONVERSATION_NOT_EXISTS);
        }
    }

    @Override
    public ConversationDO getConversation(Integer id) {
        return conversationMapper.selectById(id);
    }

    @Override
    public ConversationDO getLastedAssistantChat(String conversationId) {
        return conversationMapper.selectOne(new LambdaQueryWrapper<ConversationDO>()
                .eq(ConversationDO::getConversationId, conversationId)
                .eq(ConversationDO::getRole, "assistant")
                .orderByDesc(ConversationDO::getId)
                .last("LIMIT 1"));
    }

    @Override
    public PageResult<ConversationDO> getConversationPage(AppConversationPageReqVO pageReqVO) {
        return conversationMapper.selectPage(pageReqVO);
    }

    @Override
    public JSONObject statisticsConversation(String conversationId) {
        List<ConversationDO> conversationDOList = conversationMapper.selectList(new LambdaQueryWrapper<ConversationDO>()
                .eq(ConversationDO::getConversationId, conversationId));
        long chat_times = conversationDOList.stream().filter(conversationDO -> "user".equals(conversationDO.getRole())).count();
        long chat_words = conversationDOList.stream().mapToInt(conversationDO -> conversationDO.getContent().replace(" ", "").replace("\n", "").length())
                .sum();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("chat_times", chat_times);
        jsonObject.put("chat_words", chat_words);
        return jsonObject;
    }
}
